/// <reference path="ZYCLib.PlugIn.ShoppingCart.js" />

var _PublicServerUrl = "http://publicservice.net/Ajax/AjaxHandle.ashx?CommandName=";


Date.prototype.Format = function (formatting) {
    var year = this.getFullYear().toString(),
        month = (this.getMonth() + 1),
        day = this.getDate(),
        hours = this.getHours(),
        minutes = this.getMinutes(),
        seconds = this.getSeconds(),
        milliseconds = this.getMilliseconds();

    var fmts = {
        "M+": month,
        "d+": day,
        "h+": hours,
        "m+": minutes,
        "s+": seconds,
        "f": milliseconds
    };

    if (/(y+)/g.test(formatting)) {
        formatting = formatting.replace(RegExp.$1, RegExp.$1.length === 4 ? year : year.substr(year.length - RegExp.$1.length));
    }

    for (var fmt in fmts) {
        if (fmts.hasOwnProperty(fmt)) {
            var regexp = new RegExp(["(", fmt, ")"].join(""));
            if (regexp.test(formatting)) {
                var _$1 = regexp.exec(formatting)[0],
                    val = fmts[fmt];
                formatting = formatting.replace(regexp, (_$1.length === 1 || val > 10) ? val : [0, val].join(""));
            }
        }
    }
    return formatting;
};

var ZYCLib = (function ($) {
    document.domain = window.location.hostname.split('.').slice(1).join('.');
    if (!window.console) {
        window.console = {};
        window.console.log = function () {
        };
    }

    var _d = window.location.hostname;
    _d = "." + _d.substring(_d.lastIndexOf(".", _d.lastIndexOf(".") - 1) + 1);
    var currentUser = { UserName: "游客", PerID: 0, UserID: 0 };
    var requirejs = [];
    var loadingjs = false;
    var loadjs = function () {
        if (loadingjs) return;

        if (requirejs.length == 0) return;
        loadingjs = true;
        var js = requirejs.shift();
        var url = js.url;
        var id = js.id;
        var fCallback = js.fnCallBack;
        if ($("#" + id).length > 0) {
            loadingjs = false;
            loadjs();
            return;
        }
        if (!url.startsWith("http"))
            url = (location.protocol === "https:" ? "" : ("http://i" + _d)) + "/Scripts/" + url + ".js";

        var script = document.createElement("script");
        script.setAttribute("charset", "gb2312");
        script.setAttribute("type", "text/javascript");
        script.setAttribute("src", url);
        script.setAttribute("id", id);
        document.getElementsByTagName("head")[0].appendChild(script);
        script.onreadystatechange = function () {
            if (this.readyState == "loaded" || this.readyStaate == "complete") {
                loadingjs = false;
                loadjs();
                fCallback();
            }
        };
        script.onload = function () {
            loadingjs = false;
            loadjs();
            fCallback();
        };
    };
    var requireJs = function (url, id, fCallback) {

        requirejs.push({ url: url, id: id, fnCallBack: fCallback });
        loadjs();

    };
    var loginurl = "/Signin/Login?returnurl=" + escape(location.href);
    var loginurlNR = "/Signin/Login?";
    var onSetUserInfo = function () { };
    var callBack = function (fn) {
        if (fn != null && $.isFunction(fn)) {
            var args = [];
            for (var i = 1, j = arguments.length; i < j; i++) args.push(arguments[i]);
            return fn.apply(this, args);
        }
    };
    ///用于调试跟踪开始执行事件和执行结束时间
    var DebugTime = function (fmt) {
        if (typeof fmt === "undefined") fmt = "yyyy-MM-dd hh:mm:ss.f";
        var date = new Date();
        console.log(date.Format(fmt));
    };
    return {
        RegNameSpace: function (fullNS) {
            /// <summary>注册名称空间</summary>
            var domains = fullNS.split(".");
            var cur_domain = ZYCLib;
            for (var i = 0; i < domains.length; i++) {
                var domain = domains[i];
                if (typeof (cur_domain[domain]) === "undefined") {
                    cur_domain[domain] = {};
                }
                cur_domain = cur_domain[domain];
            }
            return cur_domain;
        },
        ImportNameSpace: function (fullNS, shortdomain) {
            if (!shortdomain) {
                var domains = fullNS.split(".");
                shortdomain = domains[domains.length - 1];
            }
            if (typeof window[shortdomain] === "undefined") {
                window[shortdomain] = ZYCLib.RegNameSpace(fullNS);
                return window[shortdomain];
            } else {
                throw new Error("名称空间冲突,请使用其他名称代替");
            }
        },
        Domain: _d,
        HttpWWWDomain: "http://www" + _d,
        DistributionDomain: "dsc" + _d,
        MerchantDomain: "sh" + _d,
        AdminDomain: "admin" + _d,
        ResourcesDomain: "i" + _d,
        LoginUrlNR: loginurlNR,
        LoginReqired: function (json) {

            var reqiredJson = { Url: loginurl, MsgContent: "您尚未登录, 请登录后再使用该功能", MsgTitle: "需要登录" };
            $.extend(reqiredJson, json, true);
            ZYCLib.UI.MessageBox.Confirm(reqiredJson.MsgContent, function () { location.href = reqiredJson.Url; }, reqiredJson.MsgTitle);
        },
        LoginUrl: function () {

            return loginurl;
        },
        Require: requireJs,
        SetUserInfo: function (json) {
            $.extend(currentUser, json, true);
            if (currentUser.PerID > 0) {
                //requireJs("PlugIn/HeartBeat", "HeartBeat", function () { ZYCLib.PlugIn.HeartBeatPackage.Start(); });
                onSetUserInfo();
            }
        },
        SetLoginUrl: function (lgUrl) {
            loginurl = lgUrl + "?returnurl=" + escape(location.href);
        },
        CurrentUser: currentUser,
        OnSetUserInfo: function (callback) {
            onSetUserInfo = callback;
        },
        CallBack: callBack,
        DEBUGTIME: DebugTime
    };
})(jQuery);
//StringBuilder
(function (namespace) {
    ZYCLib.RegNameSpace(namespace).StringBuilder = function (initString) {
        var arrBuck = new Array();
        if (initString) arrBuck.push(initString);
        return {
            Append: function (strVal) {
                /// <summary>追加文本</summary>
                /// <param name="strVal" Type="String">需要追加的字符串</param>
                /// <returns>StringBuilder</returns>
                arrBuck.push(strVal);
                return this;
            },
            AppendFormat: function () {
                /// <summary>格式化追加文本</summary>
                var arg = Array.prototype.slice.call(arguments, 0);
                var strVal = arg.shift();

                for (var i in arg) {
                    var re = eval("/\\{" + i + "\\}/g;");
                    strVal = strVal.replace(re, arg[i]);
                }
                arrBuck.push(strVal);
                return this;
            },
            Clear: function () {
                arrBuck.length = 0;
                return this;
            },
            RemoveTail: function (length) {
                length = length || 1;

                var idx = arrBuck.length - 1;
                var cutlen = arrBuck[idx].length - length;
                if (cutlen > 0)
                    arrBuck[idx] = arrBuck[idx].substring(0, arrBuck[idx].length - length);
                else
                    arrBuck.pop();
                return this;
            },
            ToString: function () {
                return arrBuck.join("");
            }
        };
    };

    //验证输入框的内容,参数说明：id 文本框ID,regStr 正则表达式,ismacth 是否匹配规则，如果true则表示匹配正则返回true,反之不匹配正则返回true
    ZYCLib.RegNameSpace(namespace).InputValidator = function (id, regStr, ismacth) {
        if (ismacth == null) {
            ismacth = true;
        }
        var isValidated = true;
        var jqCtrl = $("#" + id);
        if (jqCtrl.length > 0) {
            var val = jqCtrl.val();
            if (val === "") {
                isValidated = false;
            } else {
                if (regStr != null && regStr !== "") {
                    if (ismacth) {
                        if (!val.match(regStr)) {
                            isValidated = false;
                        }
                    } else {
                        if (val.match(regStr)) {
                            isValidated = false;
                        }
                    }
                }
            }
        }
        return isValidated;
    };

}("Text"));

//Utils --> LocalStorage,Cache
(function (namespace) {
    ZYCLib.RegNameSpace(namespace).LocalStorage = (function () {
        var isLocalStorage = window.localStorage ? true : false;

        function setCookie(key, value, seconds) {
            var argv = arguments;
            var argc = argv.length;
            var expires;
            if (seconds == null) {
                expires = new Date(2100, 11, 31);
            } else {
                expires = new Date();
                expires.setTime(expires.getTime() + seconds * 1000);
            }
            var path = (3 < argc) ? argv[3] : "/";
            var domain = (4 < argc) ? argv[4] : null;
            if (!domain) {
                domain = document.domain;
                domain = domain.substring(domain.lastIndexOf(".", domain.lastIndexOf(".") - 1) + 1);
            }
            var secure = (5 < argc) ? argv[5] : false;
            document.cookie = key + "=" + escape(value) + ";expires=" + expires.toGMTString() + (path == null ? "" : ";path=" + path) + (domain == "" ? "" : ";domain=" + domain) + (secure == null ? ";secure" : "");
        }

        function removeCookie(key) {
            //document.cookie = key + "=''";
            setCookie(key, "", -1);
        }

        function getCookie(key, nounescape) {
            var p = key + "=";
            var start = document.cookie.indexOf(p);
            if (start == -1) return null;
            var end = document.cookie.indexOf(";", start);
            var v = document.cookie.substring(start + p.length, (end > start ? end : document.cookie.length));
            return !nounescape ? unescape(v) : v;
        }


        var set = function (key, value) {
            if (isLocalStorage) {
                window.localStorage.setItem(key, value);
            } else {
                setCookie(key, value);
            }
        };
        var get = function (key) {
            if (isLocalStorage) {
                return window.localStorage.getItem(key);
            } else {
                return getCookie(key, false);
            }
        };
        var remove = function (key) {
            if (isLocalStorage) {
                localStorage.removeItem(key);
            } else {
                removeCookie(key);
            }
        };

        return {
            Get: function (key) {
                return get("__localStorage__" + key);
            },
            Set: function (key, value) {
                set("__localStorage__" + key, value);
            },
            Remove: function (key) {
                remove("__localStorage__" + key);
            },
            GetCookie: getCookie,
            SetCookie: setCookie,
            RemoveCookie: removeCookie
        };

    })();
    ZYCLib.RegNameSpace(namespace).Cache = (function () {

        var cachebucket = {};
        return {
            Get: function (key, cachePre, callback) {
                cachePre = cachePre || "";
                var result = cachebucket[cachePre + key];
                if (result) return result;
                if (callback) {
                    result = cachebucket[cachePre + key] = callback(key);
                }
                return result;
            },
            Set: function (key, value, cachePre) {
                cachePre = cachePre || "";
                cachebucket[cachePre + key] = value;
            },
            Remove: function (key, cachePre) {
                cachePre = cachePre || "";
                delete cachebucket[cachePre + key];
            }
        };

    })();
    //赵睿（事件代理）
    ZYCLib.RegNameSpace(namespace).EventProxy = (function () {
        var eventProxy = function () {
            var that = this;

            var array = [], slice = array.slice, splice = array.splice;

            that.on = function (name, callback, context) {
                if (!that.eventsApi(that, "on", name, context) || !callback)
                    return that;
                that._events || (that._events = {});
                var events = that._events[name] || (that._events[name] = []);
                events.push({
                    callback: callback,
                    context: context,
                    ctx: context || that
                });
                return that;
            };
            that.trigger = function (name) {
                if (!that._events) return that;
                var events = that._events[name];
                if (events) that.triggerEvents(events, arguments);
                var allEvents = that._events.all;
                if (allEvents) that.triggerEvents(allEvents, arguments);
                return that;
            };
            that.eventsApi = function (obj, action, name, rest) {
                if (!name) return true;
                if (typeof name === "object") {
                    for (var key in name) {
                        obj[action].apply(obj, [key, name[key]].concat(rest));
                    }
                    return true;
                }
                return true;
            };
            that.triggerEvents = function (events, args) {
                var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
                switch (args.length) {
                    case 0:
                        while (++i < l) (ev = events[i]).callback.call(ev.ctx);
                        return;

                    case 1:
                        while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1);
                        return;

                    case 2:
                        while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2);
                        return;

                    case 3:
                        while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3);
                        return;

                    default:
                        while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
                }
            };
            that.waitAll = function () {
                if (arguments.length < 2) return;
                var that = this, callback = slice.call(arguments, arguments.length - 1).shift(), args = slice.call(arguments, 0, arguments.length - 1), argLen = args.length;
                var dataArray = [];

                that.on("all", function (name) {
                    var index = args.indexOf(name);
                    if (index >= 0) {
                        args.splice(index, 1);
                        var data = slice.call(arguments, 1);
                        dataArray.push(data);
                        if (!args.length && dataArray.length === argLen) {
                            callback.apply(that, dataArray);
                        }
                    }
                });
            };
        };
        return eventProxy;
    })();
    ZYCLib.RegNameSpace(namespace).Ajax = (function () {
        var busying = false;
        var fancyTimer = null, fancyDelayTime, fancyPluginUse = !!$.fancybox;

        function onShowAndHidLoading(delay) {
            fancyDelayTime = delay || 2000;
            $(document).ajaxStart(function () {
                fancyShowLoading();
            });
            $(document).ajaxStop(function () {
                fancyHideLoading();
            });

            function fancyShowLoading() {
                fancyHideLoading();
                fancyTimer = setTimeout(function () {
                    $.fancybox.showLoading();
                }, fancyDelayTime);
            }
            function fancyHideLoading() {
                $.fancybox.hideLoading();
                if (fancyTimer) {
                    clearTimeout(fancyTimer);
                    fancyTimer = null;
                }
            }
        }

        function onShowAndHidLoadingBusying() {
            $(document).ajaxStart(function () {
                if (busying) {
                    alert("正在处理前一个请求，请稍后......");
                    return;
                }
                busying = true;
            });
            $(document).ajaxStop(function () {
                if (busying) {
                    busying = false;
                }
            });
        }

        return {
            onShowAndHidLoading: fancyPluginUse ? onShowAndHidLoading : onShowAndHidLoadingBusying,
            onShowAndHidLoadingBusying: onShowAndHidLoadingBusying
        };
    })();

    ZYCLib.RegNameSpace(namespace).UriHelper = (function () {
        var self;

        var params = function (search) {
            return search.split("&");
        };

        var init = function (pathName) {
            self = this;
            var loc = window.location;
            self.host = loc.hostname;
            self.pathName = (typeof pathName === "undefined") ? loc.pathname : pathName;
            self.protocol = loc.protocol;
            self.port = loc.port;
            var index = loc.search.indexOf("?");
            self.search = index > -1 ? loc.search.substr(index + 1, loc.search.length - index - 1) : "";
            self.href = loc.href;
            return self;
        };

        var toString = function (jsonObj) {
            if (typeof jsonObj === "undefined" || null === jsonObj) return self.href;
            var sParams = params(self.search);
            for (var p in jsonObj) {
                if (jsonObj.hasOwnProperty(p)) {
                    if (self.search.toLowerCase().indexOf(p.toLowerCase()) > -1) {
                        for (var i = 0; i < sParams.length; i++) {
                            if (sParams[i].toLowerCase().indexOf(p.toLowerCase()) > -1) {
                                var kv = sParams[i].split("=");
                                sParams[i] = kv[0] + "=" + jsonObj[p];
                            }
                        }
                    } else {
                        sParams.push(p + "=" + jsonObj[p]);
                    }
                }
            }

            var esParam = "";
            for (var ii = 0; ii < sParams.length; ii++) {
                if ("" !== sParams[ii]) {
                    if ("" === esParam) esParam = "?" + sParams[ii];
                    else esParam = esParam + "&" + sParams[ii];
                }
            }

            return self.protocol + "//" + self.host + self.pathName + esParam;
        };

        var nothingSearch = function () {
            return self.protocol + "//" + self.host + self.pathName;
        }

        return {
            Init: init,
            ToString: toString,
            NothingSearch: nothingSearch
        };
    })();

    ZYCLib.RegNameSpace(namespace).Builder = (function () {
        function BuildFormAndSubmit(requestType, action, target, items) {
            var tmpForm = document.createElement("form");
            document.body.appendChild(tmpForm);
            tmpForm.method = requestType;
            tmpForm.action = action;
            tmpForm.target = target;
            items = items || [];
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                var newElement = document.createElement("input");
                newElement.setAttribute("id", item.Id);
                newElement.setAttribute("name", item.Name);
                newElement.setAttribute("type", item.Type);
                newElement.setAttribute("value", item.Value);
                tmpForm.appendChild(newElement);
            }
            tmpForm.submit();
        };

        return {
            BuildFormAndSubmit: function (requestType, action, target, items) {
                BuildFormAndSubmit(requestType, action, target, items);
            }
        };
    })();
})("Utils");

//Menu,Form,Calendar,MessageBox,PageCute
(function (namespace, $) {
    ZYCLib.RegNameSpace(namespace).DropDownList = function (parent) {
        parent = $(parent);
        var ddBox = parent.find("div[subtype=ddmenu]");
        if (!ddBox) return;
        ddBox.bind("click", function (event) {
            hideItemMenu();
            parent.find("ul").removeClass("none");
            ddBox.find("b").addClass("rotate");
            event.stopPropagation();
        });

        var hideItemMenu = function () {
            $("div[subtype='ddmenu']").each(function (index, item) {
                $(item.parentNode).find("ul").addClass("none");
            });
        };

        var setValue = function (val, txt) {
            if (!txt) {
                var lis = parent.find("ul")[0].childNodes;
                $(lis).each(function (index, item) {
                    if ($(item).attr("val") == val) {
                        txt = $(item).attr("txt");
                    }
                });
            }
            parent.find('div[subtype="ddmenu"] span').html(txt);
            parent.find('ul').addClass("none");
            parent.find('b').removeClass("rotate");
            parent.find('input[type="hidden"]').val(val);
        };

        parent.find("ul").bind("click", function (event) {
            var e = event.target;
            if (e.tagName == "LI") {
                setValue($(e).attr("val"), $(e).attr("txt"));
                parent.trigger("widget:onValueChanged", { dom: e });
                return false;
            }
            return true;
        });

        ZYCLib.Utils.Cache.Get("ddmenu_bindFlag", "document.body.event.click.", function () {
            $(document.body).bind("click", hideItemMenu);
            return 1;
        });

        return {
            SetValue: setValue
        };
    };

    ZYCLib.RegNameSpace(namespace).Form = (function () {

        var validate = function (form, fnShowError) {
            var result = true;
            fnShowError = fnShowError || function (msg, focusdom) {
                ZYCLib.UI.MessageBox.Alert(msg, 0, function () {
                    focusdom.focus();
                });
            };
            var regs = {
                username: {
                    reg: /^[\w\u4e00-\u9fa5]{2,16}$/,
                    msg: "用户名格式不合法!",
                    notAllow:
                    [
                        { reg: /^\d+$/, msg: "用户名不能为纯数字!" },
                        { reg: /^admin\d+/i, msg: "用户名不能为系统保留账号!" }
                    ]
                },
                zipcode: {
                    reg: /\d{6,6}/,
                    msg: "请填写正确的邮政编码！"
                },
                mobile: {
                    reg: /^1[0-9]{10}$/,
                    msg: "请填写正确的手机号码！"
                },
                "int": {
                    reg: /^[0-9]*[0-9]*$/,
                    msg: "请输入大于0的整数"
                },
                numeric: {
                    reg: /^[0-9]*$/,
                    msg: "请输入数字类型"
                },
                price: {
                    reg: /^(([1-9]\d{0,9})|0)(\.\d{1,2})?$/, //^([1-9][0-9]*(\.[0-9]{1,2})?|0\.(?!0+$)[0-9]{1,2})$
                    msg: "请输入合法的金额"
                },
                email: {
                    //reg: /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/,
                    reg: /^[\w-]+(?:\.[\w-]+)*@(?:[\w-]+\.)+[a-zA-Z]{2,7}$/,
                    msg: "邮箱格式不正确"
                },
                tel: {
                    reg: /((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)/,
                    msg: "座机格式不正确"
                },
                fax: {
                    reg: /((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)/,
                    msg: "传真格式不正确"
                },
                idcard: {
                    reg: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
                    msg: "身份证格式不正确"
                }
            };

            $("#" + form + " input,#" + form + " textarea").each(function (index, item) {
                item = $(item);
                var val = item.val();
                var placeholder = item.attr("placeholder");
                if ((val === "" || val === placeholder)) {
                    if (item.attr("required") === "required") {
                        var emptymsg = item.attr("emptymsg");
                        if (emptymsg == null || emptymsg.length == 0) {
                            if (placeholder)
                                emptymsg = "请填写" + placeholder;
                            else
                                emptymsg = "该字段为必填";
                        }

                        fnShowError(emptymsg, item);

                        result = false;
                        return false;
                    }
                } else {
                    if (val == "") {
                        return false;
                    }
                    var subtype = item.attr("subtype");
                    if (!(subtype == null || subtype.length == 0)) {
                        var regitem = regs[subtype.toLowerCase()];
                        if (regitem) {
                            if (!regitem.reg.test(val)) {
                                fnShowError(regitem.msg, item);
                                result = false;
                                return false;
                            }
                            var notallow = regitem.notAllow;
                            if (notallow) {
                                for (var i = 0, l = notallow.length; i < l; i++) {
                                    if (notallow[i].reg.test(val)) {
                                        fnShowError(notallow[i].msg, item);
                                        result = false;
                                        return false;
                                    }
                                }
                            }
                        }
                    }

                    var reg = item.attr("pattern");
                    if (!(reg == null || reg.length == 0)) {
                        if (!new RegExp(reg).test(val)) {
                            fnShowError(item.attr("patterntitle"), item);
                            result = false;
                            return false;
                        }
                    }
                }
            });
            return result;
        };

        var buildFormJsonData = function (form, json, parms) {
            parms = parms || {};
            $("#" + form + " input,#" + form + " textarea").each(function (index, item) {
                item = $(item);
                var name = item.attr("name");
                if (name != null && name != "") {
                    switch (item.attr("type")) {
                        case "checkbox":
                            if (item.attr("checked"))
                                parms[name] = item.val();
                            else
                                delete parms[name];
                            break;
                        case "radio":
                            if (item.context.checked)
                                parms[name] = item.val();
                            break;
                        case "button":
                            break;
                        default:
                            var val = item.val();
                            if (name.toLowerCase() != 'content')
                                val = val.replace("<", "").replace(">", "")
                            if (item.attr("placeholder") === val)
                                parms[name] = "";
                            else
                                parms[name] = val;
                            break;
                    }
                }
            });

            $("#" + form + " select").each(function (index, item) {
                var name = $(item).attr("name");
                if (name != "") {
                    var val = item.getValue().replace("<", "").replace(">", "");
                    if (item.attr("placeholder") === val)
                        parms[name] = "";
                    else
                        parms[name] = val;
                }
            });

            if (json) {
                for (var j in json) {
                    if (json[j] != null && json[j] != "" && json[j] != 0)
                        parms[j] = json[j];
                    else
                        delete parms[j];
                }
            }

            return parms;
        };

        var submit = function (form, json) {

            var result = false;
            if ($("#" + form).length > 0) {
                result = validate(form, json.ShowError);
                if (!result) return false;
            }

            if (json.Validate) {
                result = json.Validate();
                if (!result) return false;
            }
            var postData = {};
            if ($("#" + form).length > 0) postData = buildFormJsonData(form, json.data, {});
            else postData = json.data;
            if (json.WarpData) json.WarpData(postData);

            var onSuccess = json.OnSuccess;
            if (!onSuccess) {
                if (json.SuccessUrl) {
                    onSuccess = function () {
                        location.href = json.SuccessUrl;
                    };
                }
            }

            //ZYCLib.Web.JsonAjax.SetUrl(url);
            if (json.ConfirmMsg) {
                ZYCLib.UI.MessageBox.Confirm(json.ConfirmMsg, function () {
                    ZYCLib.Web.JsonAjax.PostData(json.Action, postData, onSuccess, json.OnComplete, json.OnErrorCodeHandler, json.isPrivate);
                }, "");
            } else {
                ZYCLib.Web.JsonAjax.PostData(json.Action, postData, onSuccess, json.OnComplete, json.OnErrorCodeHandler, json.isPrivate);
            }

            return true;
        };

        var initDateInput = function (options) {
            $("input[subtype='date']")
                .attr("readonly", "readonly")
                .on("click", function (event) {
                    $(this).Calendar(options);
                    event.stopPropagation();
                });
        };

        var submitByForm = function (action, items, requestType, target) {
            var tmpForm = document.createElement("form");
            document.body.appendChild(tmpForm);
            tmpForm.method = requestType || "POST";
            tmpForm.action = action;
            tmpForm.target = target || "_self";
            items = items || {};

            for (var name in items) {
                var val = items[name];
                if ($.isFunction(val))
                    val = ZYCLib.CallBack(val);
                var newElement = document.createElement("input");
                newElement.setAttribute("name", name);
                newElement.setAttribute("type", "hidden");
                newElement.setAttribute("value", val);
                tmpForm.appendChild(newElement);
            }
            tmpForm.submit();
        };

        var KeyUpPreventKeyCode = [
            Event.KEY_HOME, Event.KEY_END, Event.KEY_LEFT, Event.KEY_RIGHT, Event.KEY_UP,
            Event.KEY_DOWN, Event.KEY_PAGEUP, Event.KEY_PAGEDOWN
        ];

        var isControlKeyCodeForKeyUp = function (event) {
            var keyCode = event.keyCode || event.charCode;
            if ($A(KeyUpPreventKeyCode).select(function (i) {
                return i === keyCode;
            }).length === 0) {
                return true;
            }
            return false;
        };

        var validateInt = function (element) {
            element = $(element);
            var val = $.trim(element.value.replace(/[^\d]+/, ""));
            element.value = val;
        };

        var validatePrice = function (element) {
            element = $(element);
            var val = $.trim(element.value.replace(/[^\d\.]+/, "").replace(/\.(\.)+/, ""));

            var value = /\.\d{3,}/.test(val) ? (val * 1).toFixed(2) : val;
            element.value = value;

        };

        var onKeyUp = function (event) {
            var element = $(event).target;
            if (!isControlKeyCodeForKeyUp(event)) return;
            switch (element.attr("subtype")) {
                case "int":
                    validateInt(element);
                    event.stop();
                    break;
                case "price":
                    validatePrice(element);
                    event.stop();
                    break;
            }
        };

        var fomartPrice = function (event) {

            var element = $(event.target);
            var val = $.trim(element.getValue());
            if (!val.empty()) {
                var price = parseFloat(val);
                val = isNaN(price) ? new Number(0).toFixed(2) : price.toFixed(2);
                element.setValue(val);
            }
            event.stop();
        };

        var initCheckBox = function (selectall, deselect) {

            if (!selectall) {
                selectall = $("input[type=\"checkbox\"][subtype=\"selectall\"]:enabled");
                deselect = $("input[type=\"checkbox\"][subtype=\"deselect\"]");
            }

            var onItemChange = function (p) {
                var allOpts = $("input[type=\"checkbox\"][name=\"" + p.val() + "\"]:enabled");

                if (allOpts.length == 0) {
                    p.attr("disabled", "disabled");
                    return;
                }

                if (p.prop("checked")) {
                    if (allOpts.not(":checked").length > 0)
                        p.prop("checked", false);
                } else {
                    if (allOpts.not(":checked").length == 0)
                        p.prop("checked", true);
                }
            };

            selectall.each(function (index, all) {
                var allOptions = $("input[type=\"checkbox\"][name=\"" + all.value + "\"]:enabled");
                $(all).on("click", function () {
                    allOptions.each(function (idex, item) {
                        item.checked = all.checked;
                    });
                });
                allOptions.each(function (index, item) {
                    $(item).on("click", function () {
                        onItemChange($(all));
                    });
                });
                onItemChange($(all));
            });

            if (deselect) {
                deselect.each(function (index, all) {
                    var allOptions = $("input[type=\"checkbox\"][name=\"" + all.value + "\"]:enabled");
                    all.on("click", function () {
                        allOptions.each(function (index, item) {
                            item.checked = !item.checked;
                        });
                        onItemChange();
                    });
                });
            }


        };
        var initDropDownList = function () {
            var ddBox = $("div[subtype=ddmenu]");
            if (ddBox.length > 0) {
                ddBox.each(function (idx, item) {
                    ZYCLib.Utils.Cache.Get($(item).parent().attr("id"), "page.controls.ddmenu", function (key) {
                        return new ZYCLib.UI.DropDownList($("#" + key));
                    });
                });
            }
        };

        var initFormatText = function (parentid) {
            if (!parentid) parentid = $(document.body);
            $(parentid).stopObserving("keyup", onKeyUp);
            $(parentid).on("keyup", onKeyUp);

            $(parentid).find("input[type=\"text\"][subtype=\"price\"]").each(function (index, item) {
                item.stopObserving("blur", fomartPrice);
                item.on("blur", fomartPrice);
            });
        };
        return {
            InitInputDefaultText: function () { },
            InitInputDateText: initDateInput,
            InitFormatText: initFormatText,
            InitCheckBox: initCheckBox,
            InitControls: function (parentid) {
                initFormatText();
                initCheckBox();
            },
            InitDropDownList: initDropDownList,
            Validate: validate,
            SubmitByAjax: submit,
            SubmitByForm: submitByForm,
            SubmitByLocation: function (form, json, url) {
                if (!validate(form)) return;
                var parms = {};
                if (!url) parms = ZYCLib.Web.Request.ToJSON();
                parms = buildFormJsonData(form, json, parms);

                var urlgoto = ZYCLib.Web.URL.ConverJSON2URL(parms, url);
                location.href = urlgoto;
            },
            FillInputByURLParm: function (form) {
                $("#" + form + " input[type!='button']").each(function (index, item) {
                    var name = item.attr("name");
                    if (name != "") {
                        var value = ZYCLib.Web.Request.QueryString(name);
                        switch (item.type) {
                            case "checkbox":
                                if (item.value === value)
                                    item.checked = true;
                                else
                                    item.checked = false;
                                break;
                            default:
                                item.setValue(value);
                                break;
                        }
                    }
                });

                $("#" + form + " select").each(function (index, item) {
                    var name = item.attr("name");
                    if (name != "") {
                        var value = ZYCLib.Web.Request.QueryString(name);
                        item.setValue(value);
                    }
                });
            },
            FormToJsonData: buildFormJsonData
        };
    })();

    ZYCLib.RegNameSpace(namespace).Calendar = (function () {
        var defaultOptions = {
            year: "年",
            month: "月",
            months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
            weeks: ["日", "一", "二", "三", "四", "五", "六"],
            clear: "清空",
            today: "今天",
            close: "关闭",
            startYear: new Date().getFullYear()
        };

        var language,
            jqCtrl,
            CalendarContainer,
            SetCalendarCtrlValue,
            CurrentDate = "",
            PrevYearTd,
            SelectYearTd,
            NextYearTd,
            PrevMonthTd,
            SelectMonthTd,
            NextMonthTd;

        var clickCount = {
            firstClick: "0",
            secondClick: "1"
        };

        var getAbspointer = function () {
            //   var borderTop = parseInt(jqCtrl.css("border-top-width") === "" ? 0 : jqCtrl.css("border-top-width")),
            //    borderBottom = parseInt(jqCtrl.css("border-bottom-width") === "" ? 0 : jqCtrl.css("border-bottom-width")),
            //    paddingTop = parseInt(jqCtrl.css("padding-top") === "" ? 0 : jqCtrl.css("padding-top")),
            //    borderBottom = jqCtrl.css("border-bottom"),
            //    paddingBottom = parseInt((borderBottom === "" || typeof borderBottom === "undefined") ? 0 : jqCtrl.css("border-bottom")),

            var left = jqCtrl.offset().left,
                 top = jqCtrl.offset().top + jqCtrl.outerHeight();
            //top = jqCtrl.offset().top + borderTop + borderBottom + paddingTop + paddingBottom;
            console.log(jqCtrl);
            console.log(jqCtrl.offset().top);
            console.log(jqCtrl.outerHeight());
            console.log(top)
            return {
                left: left,
                top: top
            };
        }

        var getDayViewArray = function () {
            var currentDate = new Date(SetCalendarCtrlValue || (CurrentDate || new Date()));
            var _curYear = currentDate.getFullYear(),
                _curMonth = currentDate.getMonth(),
                _curDay = currentDate.getDate(),
                _curWeek = currentDate.getDay(),
                _curMonthDate = new Date(_curYear, _curMonth + 1, 0), //从1开始的 0~12
                _curMonthFirstDate = new Date(_curYear, _curMonth, 1), //从0开始的 0~11
                _curMonthMaxDay = _curMonthDate.getDate(), //当月有多少天
                _curMonthFirstDayOfWeek = _curMonthFirstDate.getDay(), //第一天星期几
                _prevMonthDate = new Date(_curYear, _curMonth, 0),
                _prevYear = _prevMonthDate.getFullYear(),
                _prevMonth = _prevMonthDate.getMonth(),
                _prevMonthMaxDay = _prevMonthDate.getDate(), //上月有多少天
                _nextMonthDate = new Date(_curYear, _curMonth + 2, 0),
                _nextYear = _nextMonthDate.getFullYear(),
                _nextMonth = _nextMonthDate.getMonth();

            CurrentDate = currentDate;

            var _prevMonthLastSeventDays = [],
                _monthDays = [],
                _nextDays = [],
                _nextMonthDayCount = 1;
            for (var i = _prevMonthMaxDay; i > 0; i--) {
                if (_prevMonthLastSeventDays.length === _curMonthFirstDayOfWeek) break;
                _prevMonthLastSeventDays.push(i);
            }

            for (var _day = 1; _day <= _curMonthMaxDay; _day++) {
                _monthDays.push(_day);
            }

            while ((_prevMonthLastSeventDays.length + _curMonthMaxDay + _nextDays.length) < 42) {
                _nextDays.push(_nextMonthDayCount++);
            }

            return {
                prevMonth: {
                    year: _prevYear,
                    month: _prevMonth,
                    days: _prevMonthLastSeventDays.sort(function (a, b) { return a - b; })
                },
                curMonth: {
                    year: _curYear,
                    month: _curMonth,
                    days: _monthDays
                },
                nextMonth: {
                    year: _nextYear,
                    month: _nextMonth,
                    days: _nextDays
                },
                curDay: _curDay,
                curWeek: _curWeek
            }
        }

        var resetCalendarYearMonthRelated = function () {
            $("#Calendar_Year_Month_Select_Container").remove();
            SelectYearTd.attr("click-count", clickCount.firstClick);
            SelectMonthTd.attr("click-count", clickCount.firstClick);
        }

        var bindDay = function () {
            var dayViewArray = getDayViewArray();
            SelectYearTd
                .attr("year", dayViewArray.curMonth.year)
                .text(dayViewArray.curMonth.year + language.year);
            SelectMonthTd
                .attr("month", dayViewArray.curMonth.month)
                .text((dayViewArray.curMonth.month + 1) + language.month);
            $("#Calendar_Day_Select_Container td").css({ cursor: "pointer", "background-color": "" });

            $.each($("#Calendar_Day_Select_Container td"), function (index, item) {
                var _td = $(item);
                if (dayViewArray.curDay === dayViewArray.curMonth.days[index - dayViewArray.prevMonth.days.length]) //选中日期等于本月的某日设置那日背景
                    $(item).css({ cursor: "pointer", "background-color": "#808080" });

                var year = dayViewArray.prevMonth.year,
                    month = dayViewArray.prevMonth.month,
                    day = dayViewArray.prevMonth.days[index];

                if (index >= dayViewArray.prevMonth.days.length && index < (dayViewArray.prevMonth.days.length + dayViewArray.curMonth.days.length)) {
                    year = dayViewArray.curMonth.year;
                    month = dayViewArray.curMonth.month;
                    day = dayViewArray.curMonth.days[index - dayViewArray.prevMonth.days.length];
                } else if (index >= (dayViewArray.prevMonth.days.length + dayViewArray.curMonth.days.length) && index < 42) {
                    year = dayViewArray.nextMonth.year;
                    month = dayViewArray.nextMonth.month;
                    day = dayViewArray.nextMonth.days[index - dayViewArray.curMonth.days.length - dayViewArray.prevMonth.days.length];
                }

                _td
                    .attr("year", year)
                    .attr("month", month)
                    .attr("day", day)
                    .text(day);
            });
        }

        var getYears = function () {
            var _curYear = new Date(CurrentDate).getFullYear(),
                _years = [];
            for (var i = _curYear; i > (_curYear - 6) ; i--) {
                _years.push(i);
            }
            for (var ii = (_curYear + 1) ; ii <= (_curYear + 6) ; ii++) {
                _years.push(ii);
            }

            var temp = _years.sort(function (a, b) { return a - b; });
            $("#prev_page_year_td").attr("year", temp[0]);
            $("#next_page_year_td").attr("year", temp[temp.length - 1]);
            return temp;
        }

        var updateYearData = function (startYear, isPrev) {
            var _year;
            if (isPrev) { //向前翻
                _year = parseInt(startYear) - 7;
                CurrentDate = new Date(CurrentDate).setFullYear(_year);
            } else {
                _year = parseInt(startYear) + 6;
                CurrentDate = new Date(CurrentDate).setFullYear(_year);
            }

            var _years = getYears();
            $.each($("#Calendar_Year_Month_Select_Container td"), function (index, item) {
                var _td = $(item);
                _td
                    .attr("year", _years[index])
                    .text(_years[index] + language.year);
            });
        }

        var buildYearMonthHtml = function (isYear) {
            resetCalendarYearMonthRelated();
            var html = [];
            html.push('    <div id="Calendar_Year_Month_Select_Container" style="width: 100%; margin: 0; padding: 0; top: 22px; left: 0; position: relative; z-index: 10005; background-color: #FFF; display: none;">');
            html.push('        <table border="0" cellpadding="0" cellspacing="1" style="width: 100%; text-align: center;">');
            if (isYear)
                html.push('            <tr><th style="cursor: pointer; width: 33.3%;" id="prev_page_year_td"><</th><th></th><th style="cursor: pointer; width: 33.3%;" id="next_page_year_td">></th></tr>');

            for (var i = 0; i < 4; i++) {
                html.push('            <tr><td style="cursor: pointer; width: 33.3%;"></td><td style="cursor: pointer;"></td><td style="cursor: pointer; width: 33.3%;"></td></tr>');
            }

            html.push('        </table>');
            html.push('    </div>');
            $(html.join("")).appendTo(CalendarContainer);

            $("#Calendar_Year_Month_Select_Container th").on("click", function (event) {
                event.stopPropagation();
            });

            $("#prev_page_year_td").on("click", function (evt) {
                updateYearData($(this).attr("year"), true);
                evt.stopPropagation();
            });
            $("#next_page_year_td").on("click", function (evt) {
                updateYearData($(this).attr("year"), false);
                evt.stopPropagation();
            });
        }

        var bindYear = function () {
            buildYearMonthHtml(true);
            //绑定年份数据 Start
            var _years = getYears();
            $.each($("#Calendar_Year_Month_Select_Container td"), function (index, item) {
                var _td = $(item);
                _td
                    .on("click", function (event) {
                        var __td = $(this),
                            year = __td.attr("year");
                        if (typeof year === "undefined" || year === "0") {
                            event.stopPropagation();
                            return;
                        }
                        SetCalendarCtrlValue = new Date(SetCalendarCtrlValue).setFullYear(year);
                        bindDay();
                        SelectYearTd
                            .attr("year", year);
                        $("#Calendar_Year_Month_Select_Container").slideUp(500, function () {
                            resetCalendarYearMonthRelated();
                        });
                        event.stopPropagation();
                    })
                    .on("mouseover", function (event) {
                        var __td = $(this);
                        __td.css({ "font-weight": "bold", "cursor": "pointer", "font-style": "italic", "background-color": "#008000" });
                        event.stopPropagation();
                    })
                    .on("mouseout", function (event) {
                        var __td = $(this);
                        __td.css({ "font-weight": "", "font-style": "", "background-color": "" });
                        event.stopPropagation();
                    })
                    .attr("year", _years[index])
                    .text(_years[index] + language.year);
            });
            //绑定年份数据 End
        }

        var bindMonth = function () {
            buildYearMonthHtml(false);
            //绑定月份数据 Start
            $.each($("#Calendar_Year_Month_Select_Container td"), function (index, item) {
                var _td = $(item);
                _td
                    .on("click", function (event) {
                        var __td = $(this),
                            month = __td.attr("month");
                        SetCalendarCtrlValue = new Date(SetCalendarCtrlValue).setMonth(month);
                        bindDay();
                        SelectMonthTd
                            .attr("month", month);
                        $("#Calendar_Year_Month_Select_Container").slideUp(500, function () {
                            resetCalendarYearMonthRelated();
                        });
                        event.stopPropagation();
                    })
                    .on("mouseover", function (event) {
                        var __td = $(this);
                        __td.css({ "font-weight": "bold", "cursor": "pointer", "font-style": "italic", "background-color": "#008000" });
                        event.stopPropagation();
                    })
                    .on("mouseout", function (event) {
                        var __td = $(this);
                        __td.css({ "font-weight": "", "font-style": "", "background-color": "" });
                        event.stopPropagation();
                    })
                    .attr("month", index)
                    .text(language.months[index]);
            });
            //绑定月份数据 End
        }

        var hide = function () {
            //CalendarContainer.hide();
            CalendarContainer.remove();
        }

        var bindEvent = function () {

            //#region 年份选择按钮事件绑定 Start
            PrevYearTd.on("click", function (event) {
                resetCalendarYearMonthRelated();
                var year = new Date(CurrentDate).getFullYear();
                SetCalendarCtrlValue = new Date(SetCalendarCtrlValue).setFullYear(--year);
                bindDay();
                event.stopPropagation();
            });
            SelectYearTd.on("click", function (event) {
                var _td = $(this),
                    _clickCount = _td.attr("click-count");
                if (typeof (_clickCount) === "undefined" || _clickCount === clickCount.firstClick) {
                    bindYear();
                    _td.attr("click-count", clickCount.secondClick);
                    $("#Calendar_Year_Month_Select_Container").slideDown(500);
                } else {
                    $("#Calendar_Year_Month_Select_Container").slideUp(500, function () {
                        resetCalendarYearMonthRelated();
                    });
                }
                event.stopPropagation();
            });
            NextYearTd.on("click", function (event) {
                resetCalendarYearMonthRelated();
                var year = new Date(CurrentDate).getFullYear();
                SetCalendarCtrlValue = new Date(SetCalendarCtrlValue).setFullYear(++year);
                bindDay();
                event.stopPropagation();
            });
            //#endregion 年份选择按钮事件绑定 End

            //#region 月份选择按钮事件绑定 Start
            PrevMonthTd.on("click", function (event) {
                resetCalendarYearMonthRelated();
                var month = new Date(CurrentDate).getMonth();
                SetCalendarCtrlValue = new Date(SetCalendarCtrlValue).setMonth(--month);
                bindDay();
                event.stopPropagation();
            });
            SelectMonthTd.on("click", function (event) {
                var _td = $(this),
                    _clickCount = _td.attr("click-count");
                if (typeof (_clickCount) === "undefined" || _clickCount === clickCount.firstClick) {
                    bindMonth();
                    _td.attr("click-count", clickCount.secondClick);
                    $("#Calendar_Year_Month_Select_Container").slideDown(500);
                } else {
                    $("#Calendar_Year_Month_Select_Container").slideUp(500, function () {
                        resetCalendarYearMonthRelated();
                    });
                }
                event.stopPropagation();
            });
            NextMonthTd.on("click", function (event) {
                resetCalendarYearMonthRelated();
                var month = new Date(CurrentDate).getMonth();
                SetCalendarCtrlValue = new Date(SetCalendarCtrlValue).setMonth(++month);
                bindDay();
                event.stopPropagation();
            });
            //#endregion 月份选择按钮事件绑定 End

            //#region   每天事件绑定 Start
            var oldBackgroundColor;
            $("#Calendar_Day_Select_Container td")
                .on("click", function (event) {
                    var __td = $(this),
                        _year = __td.attr("year"),
                        _month = parseInt(__td.attr("month")) + 1,
                        _day = __td.attr("day");
                    $("#Calendar_Day_Select_Container td").css({ cursor: "pointer", "background-color": "" });
                    __td.css({ cursor: "pointer", "background-color": "#808080" });
                    jqCtrl.val([_year, _month, _day].join("-"));
                    hide();
                    resetCalendarYearMonthRelated();
                    event.stopPropagation();
                })
                .on("mouseover", function (event) {
                    var __td = $(this);
                    oldBackgroundColor = __td.css("background-color");
                    __td.css({ "font-weight": "bold", "cursor": "pointer", "font-style": "italic", "background-color": "#008000" });
                    event.stopPropagation();
                })
                .on("mouseout", function (event) {
                    var __td = $(this);
                    __td.css({ "font-weight": "", "font-style": "", "background-color": oldBackgroundColor });
                    event.stopPropagation();
                });
            //#endregion 每天事件绑定 End

            $("#btnClear").on("click", function (event) {
                jqCtrl.val("");
                //hide();
                event.stopPropagation();
            });
            $("#btnToday").on("click", function (event) {
                var date = new Date();
                jqCtrl.val([date.getFullYear(), date.getMonth() + 1, date.getDate()].join("-"));
                hide();
                event.stopPropagation();
            });
            $("#btnClose").on("click", function (event) {
                hide();
                event.stopPropagation();
            });

            $(document.body).on("click", function (event) {
                hide();
                event.stopPropagation();
            });
        }

        var getGlobalCtrlVariable = function () {
            CalendarContainer = $("#CalendarContainer");
            PrevYearTd = $("#prev_year_td");
            PrevMonthTd = $("#prev_month_td");
            SelectYearTd = $("#select_year_td");
            SelectMonthTd = $("#select_month_td");
            NextMonthTd = $("#next_month_td");
            NextYearTd = $("#next_year_td");
        }

        var draw = function () {
            var html = new Array();
            html.push('<div id="CalendarContainer" style="width: 242px; top: 330px; left: 400px; position: absolute; z-index: 10000; display:none;">');
            html.push('    <div style="width: 100%; margin: 0; padding: 0; top: 0; left: 0; position: absolute; z-index: 10001; background: #EEF;">');
            html.push('        <div>');
            html.push('            <table border="0" cellpadding="0" cellspacing="1" style="width: 100%; text-align: center;">');
            html.push('                <tr><td id="prev_year_td" style="cursor: pointer;"><<</td><td id="prev_month_td" style="cursor: pointer;"><</td><td id="select_year_td" style="cursor: pointer;">2016' + language.year + '</td><td id="select_month_td" style="cursor: pointer;">4' + language.month + '</td><td id="next_month_td" style="cursor: pointer;">></td><td id="next_year_td" style="cursor: pointer;">>></td></tr>');
            html.push('            </table>');
            html.push('        </div>');
            html.push('        <div id="Calendar_Day_Select_Container" style="width: 100%;">');
            html.push('            <table border="0" cellpadding="0" cellspacing="1" style="width: 100%; text-align: center;">');
            html.push('                <thead>');
            html.push('                    <tr>');
            $.each(language.weeks, function (index, item) {
                html.push('                        <th>' + item + '</th>');
            });
            html.push('                    </tr>');
            html.push('                </thead>');
            html.push('                <tbody>');
            for (var i = 0; i < 6; i++) {
                html.push('                    <tr>');
                for (var j = 0; j < 7; j++) {
                    html.push('                        <td style="cursor: pointer;"></td>');
                }
                html.push('                    </tr>');
            }
            html.push('                </tbody>');
            html.push('            </table>');
            html.push('        </div>');
            html.push('        <div id="Calendar_Foot_Container" style="width: 100%;">');
            html.push('            <table border="0" cellpadding="0" cellspacing="1" style="width: 100%; text-align: center;">');
            html.push('                <tr><td><input type="button" id="btnClear" value="' + language.clear + '"/></td><td><input type="button" id="btnToday" value="' + language.today + '"/></td><td><input type="button" id="btnClose" value="' + language.close + '"/></td></tr>');
            html.push('            </table>');
            html.push('        </div>');
            html.push('    </div>');
            html.push('</div>');

            $(html.join("")).appendTo(document.body);
            //bindDay();
            getGlobalCtrlVariable();
            bindEvent();

            $("#Calendar_Day_Select_Container th, #Calendar_Foot_Container td").on("click", function (event) {
                event.stopPropagation();
            });
        }

        $.fn.extend({
            Calendar: function (options) {
                return this.each(function () {
                    if ($("#CalendarContainer").length > 0)
                        $("#CalendarContainer").remove();
                    jqCtrl = $(this);
                    language = $.extend({}, defaultOptions, options);

                    draw();
                    var val = jqCtrl.val(),
                        offset = getAbspointer(jqCtrl),
                    SetCalendarCtrlValue = val.replace(/-/g, "/");
                    CalendarContainer
                        .css({ left: offset.left, top: offset.top })
                        .show(0, function () {
                            bindDay();
                        });
                });
            }
        });
    })();

    var MessageBox = function () { };
    MessageBox.prototype = {
        container: null,
        showFlag: false,
        msgQueue: null,
        jsonData: null,
        timerId: 0,
        hide: function (doNotFireEvent) {
            var self = this;
            $("#mask").hide();
            $("#containerMsgBox").fadeOut(0);

            if (self.timerId > 0) {
                clearTimeout(self.timerId);
            }

            if (!doNotFireEvent)
                self.afterHide();
            self.showFlag = false;
        },
        emptyFunction: function () { },
        onYesButtonClick: null,
        onCloseCallBack: null,
        afterHide: null,
        buildHtml: function () {
            var self = this;
            if (self.container) return;

            var htmlArray = ['<div id="mask" style="display:none;"></div><div tabindex="0" id="containerMsgBox" class="none">',
                '<div class="nui-msgbox-hd">',
                '<span id="nui-msgbox-hd"></span>',
                '<a id="btnMsgBoxClose" title="关闭"></a>',
                '</div>',
                '<div class="nui-msgbox-bd">',
                '<div class="nui-msgbox-iconText ">',
                '<span id="spanMsgBoxIcon"></span>',
                '<div id="divMsgBoxContent">',
                '</div>',
                '</div>',
                '</div>',
                '<div class="nui-msgbox-ft">',
                '<div class="nui-msgbox-ft-text"></div>',
                '<div class="nui-msgbox-ft-btns">'];
            if (self.jsonData.buttons >= 1) {
                htmlArray.push('<div role="button" tabindex="0" >');
                htmlArray.push('<input type="button" id="btnMsgBoxYes" value="确 定" />');
                htmlArray.push('</div>');
            }
            if (self.jsonData.buttons >= 2) {
                htmlArray.push('<div role="button" tabindex="0">');
                htmlArray.push('<a id="btnMsgBoxNo">取 消</a>');
                htmlArray.push('</div>');
            }
            htmlArray.push('</div>');
            htmlArray.push('</div>');
            htmlArray.push('</div>');
            var html = htmlArray.join('\r');
            if ($("#messageBoxContainer").length === 0) {
                $(["<span id='messageBoxContainer'>", html, "</span>"].join("")).appendTo(document.body);
            }
            else {
                $("#messageBoxContainer").html(html);
            }

            self.container = $("#containerMsgBox");
            self.container.on("click", function (event) {
                var element = $(event.target);
                switch (element.attr("id")) {
                    case "btnMsgBoxClose":
                        self.hide();
                        self.onCloseCallBack();
                        break;
                    case "btnMsgBoxNo":
                        self.hide();
                        self.onCloseCallBack();
                        break;
                    case "btnMsgBoxYes":
                        self.onYesButtonClick();
                        self.hide(true);
                        break;
                }
            });
        },
        //构造函数
        initialize: function (jsonData) {
            this.msgQueue = [];
            this.onYesButtonClick = this.emptyFunction;
            this.afterHide = this.emptyFunction;
            this.jsonData = {
                title: "提示信息",
                content: "",
                icon: "alert",
                buttons: 1,
                hideTime: 0
            };
            $.extend(this.jsonData, jsonData, true);
            if (this.jsonData.fnCallBack && $.isFunction(this.jsonData.fnCallBack))
                this.onYesButtonClick = this.jsonData.fnCallBack;
            else
                this.onYesButtonClick = this.emptyFunction;
            if (this.jsonData.fnCloseCallBack && $.isFunction(this.jsonData.fnCloseCallBack))
                this.onCloseCallBack = this.jsonData.fnCloseCallBack;
            else
                this.onCloseCallBack = this.emptyFunction;

            if (this.jsonData.buttons === 1) {
                this.afterHide = this.onYesButtonClick;
            }
        },
        show: function () {
            var self = this;
            self.buildHtml();
            $("#divMsgBoxContent").html([this.jsonData.content.replace("\r", "</br>")].join(''));
            $("#nui-msgbox-hd").html(this.jsonData.title);
            $("#spanMsgBoxIcon").addClass(this.jsonData.icon);
            $("#mask").show();
            self.container.show(0, function () {
                if (self.jsonData.hideTime && self.jsonData.hideTime > 0) {
                    self.timerId = setTimeout(function () { self.hide(); }, self.jsonData.hideTime * 1000);//解决定时自动关闭不能关闭提示框的问题
                }
                try {//兼容IE8
                    document.getElementById('btnMsgBoxYes').focus();
                    $("#btnMsgBoxYes").on("keydown", function (evt) {
                        var e = evt || window.event;
                        if (e.keyCode === 13) {
                            self.hide(true);
                        }
                    });
                } catch (e) { }
            });
        }
    };

    ZYCLib.RegNameSpace(namespace).FancyBox = (function () {
        return {
            Show: function (msg) {
                var htmlArray = [
                    "<div id=\"divErrMsg\" class=\"popEditBox none\">",
                    "<div class=\"popBoxHead\"><span class=\"popBoxTitle yahei\">系统提示信息</span></div>",
                    "<div class=\"popBoxBody\">",
                    msg,
                    "</div>",
                    "</div>",
                ];
                var html = htmlArray.join("\r");
                $("body").append(html);
                $.fancybox.open($("#divErrMsg"), { padding: "0" });
            }
        };
    })();

    ZYCLib.RegNameSpace(namespace).MessageBox = (function () {
        var show = function (jsonNew) {
            var messageBox = new MessageBox();
            //messageBox.__proto__.initialize(jsonNew);
            //messageBox.__proto__.show();
            messageBox.initialize(jsonNew);
            messageBox.show();
        };

        return {
            Show: show,
            Alert: function (content, hideTime, fnCallBack, title) {
                show({
                    title: title || "提示信息",
                    content: content,
                    icon: "alert",
                    buttons: 1,
                    fnCallBack: fnCallBack,
                    hideTime: hideTime
                });
            },
            Confirm: function (content, fnCallBack, title) {
                show({
                    title: title || "确认对话框",
                    content: content,
                    icon: "confirm",
                    buttons: 3,
                    fnCallBack: fnCallBack
                });
            },
            Sucess: function (content, jumpurl, hideTime, title) {
                show({
                    title: title || "保存成功",
                    content: content,
                    icon: "success",
                    buttons: 1,
                    fnCallBack: jumpurl != null && jumpurl.length > 0 ? function () {
                        window.location.href = jumpurl;
                    } : null,
                    fnCloseCallBack: jumpurl != null && jumpurl.length > 0 ? function () {
                        window.location.href = jumpurl;
                    } : null
                });
            },
            Stop: function (content, title) {
                show({ title: title || "错误提示", content: content, icon: "stop", buttons: 1 });
            }
        };
    })();
    ZYCLib.RegNameSpace(namespace).Pager = (function () {
        var PageControl = {
            //页数
            pageIndex: 1,
            //每页条数
            pageSize: 10,
            //数据量
            dataCount: 0,
            //控件编号，
            contorlId: 1,
            //翻页html标签容器
            pageTag: null,
            onPage: null,

            initialize: function (pageTag, controlId, onPage) {
                this.pageTag = $("#" + pageTag);
                this.onPage = onPage;
                this.contorlId = controlId;
            },
            refreshData: function () {
                if (this.onPage != null && this.onPage != undefined) {
                    this.onPage(this, this.pageIndex, this.dataCount, this.pageSize);
                }
            },
            //刷新界面
            render: function () {
                var self = this;
                this.renderPage();
                $("#lastPage" + this.contorlId).click(function () {
                    if (self.pageIndex <= 1) {
                        return;
                    }
                    self.pageIndex--;
                    self.refreshData();
                });
                $("#nextPage" + this.contorlId).click(function () {
                    var pageCount = self.getPageCount();
                    if (self.pageIndex >= pageCount) {
                        return;
                    }
                    self.pageIndex++;
                    self.refreshData();
                });
                this.pageTag.find(".numBtn").each(function (item) {
                    $(this).click(function () {
                        var pageCount = self.getPageCount();
                        var page = parseInt($(this).attr("pageindex"));
                        if (self.pageIndex === page) {
                            return;
                        }
                        self.pageIndex = page;
                        self.refreshData();
                    });
                });
                $("#pageNumberInput" + this.contorlId).change(function () {
                    var page = parseInt(this.value);
                    if (isNaN(page)) {
                        this.value = self.pageIndex;
                    } else {
                        this.value = page;
                    }
                    var pageCount = self.getPageCount();
                    if (page > pageCount) {
                        this.value = pageCount;
                    }
                });
                $("#pageBtn" + this.contorlId).click(function () {
                    var page = parseInt($("#pageNumberInput" + self.contorlId).val());
                    if (page < 1) {
                        page = 1;
                    }
                    if (isNaN(page)) {
                        page = self.pageIndex;
                    }
                    self.pageIndex = page;
                    self.refreshData();
                });
            },
            //获取页数
            getPageCount: function () {
                if (this.dataCount % this.pageSize === 0) {
                    return Math.floor(this.dataCount / this.pageSize);
                }
                return Math.floor(this.dataCount / this.pageSize) + 1;
            },
            //刷新翻页
            renderPage: function () {
                var result = [];
                result.push("<div class=\"pageWrap\">");
                if (this.pageIndex <= 1) {
                    result.push("<span class=\"canot\" id=\"lastPage" + this.contorlId + "\" title=\"上一页\">上一页</span>");
                } else {
                    result.push("<a class=\"page\" id=\"lastPage" + this.contorlId + "\" href=\"javascript: void 0\" title=\"上一页\">上一页</a>");
                }
                result.push("</div>");
                var pageCount = this.getPageCount();
                var showPageCount = 5;
                var minPageCount = 2;

                var pageLoopCount = pageCount > showPageCount ? showPageCount : pageCount;
                if (this.pageIndex > minPageCount + 1 && pageCount > showPageCount) {
                    result.push("<div class=\"pageWrap\"><a class=\"");
                    result.push("page numBtn\" href=\"javascript: void 0\" title=\"第");
                    result.push(1);
                    result.push("页\" pageindex=\"");
                    result.push(1);
                    result.push("\">");
                    result.push(1);
                    result.push("</a></div>");
                    result.push("<div class=\"pageWrap\"><span class=\"pageText\">…</span></div>");
                }

                for (var i = 0; i < pageLoopCount; i++) {
                    var currentPageIndex = this.pageIndex + i;
                    if (this.pageIndex < minPageCount + 2 || pageCount <= showPageCount) {
                        currentPageIndex = i + 1;
                    } else if (this.pageIndex > pageCount - minPageCount) {
                        currentPageIndex = pageCount - showPageCount + 1 + i;
                    } else {
                        currentPageIndex = currentPageIndex - minPageCount;
                    }
                    if (this.pageIndex === currentPageIndex) {
                        result.push("<div class=\"pageWrap\"><span class=\"");
                        result.push("now numBtn\" title=\"第");
                        result.push(currentPageIndex);
                        result.push("页\" pageindex=\"");
                        result.push(currentPageIndex);
                        result.push("\">");
                        result.push(currentPageIndex);
                        result.push("</span></div>");
                    } else {
                        result.push("<div class=\"pageWrap\"><a class=\"");

                        result.push("page numBtn\" href=\"javascript: void 0\" title=\"第");
                        result.push(currentPageIndex);
                        result.push("页\" pageindex=\"");
                        result.push(currentPageIndex);
                        result.push("\">");
                        result.push(currentPageIndex);
                        result.push("</a></div>");
                    }


                }
                if (this.pageIndex < pageCount - minPageCount && pageCount > showPageCount) {
                    result.push("<div class=\"pageWrap\"><span class=\"pageText\">…</span></div>");
                    result.push("<div class=\"pageWrap\"><a class=\"");
                    result.push("page numBtn\" href=\"javascript: void 0\" title=\"第");
                    result.push(pageCount);
                    result.push("页\" pageindex=\"");
                    result.push(pageCount);
                    result.push("\">");
                    result.push(pageCount);
                    result.push("</a></div>");

                }
                if (this.pageIndex >= pageCount) {
                    result.push("<div class=\"pageWrap\">");
                    result.push("<span class=\"canot\" id=\"nextPage" + this.contorlId + "\" title=\"下一页\">下一页</span>");
                    result.push("</div>");
                } else {
                    result.push("<div class=\"pageWrap\">");
                    result.push("<a class=\"page\" href=\"javascript: void 0\" id=\"nextPage" + this.contorlId + "\" title=\"下一页\">下一页</a>");
                    result.push("</div>");
                }
                result.push("<div class=\"pageWrap\">");
                result.push("<input type=\"text\" class=\"pageNum\" maxlength=\"9\" id=\"pageNumberInput" + this.contorlId + "\"></div>");
                result.push("</div>");
                result.push("<div class=\"pageWrap\"><span class=\"pageText\">页</span></div>");
                result.push("<div class=\"pageWrap\">");
                result.push("<input type=\"button\" class=\"pageBtn\" id=\"pageBtn" + this.contorlId + "\" value=\"确定\" />");
                result.push("</div>");
                this.pageTag.html(result.join(""));
            }
        };
        return {
            PageControl: function (pageTag, controlId, onPage) {
                PageControl.initialize(pageTag, controlId, onPage);
                return PageControl;
            }
        };
    })();
})("UI", jQuery);

//Web:JsonAjax,Request,URL
(function (namespace) {
    ZYCLib.RegNameSpace(namespace).JsonAjax = (function () {

        var _winDefaultLoad = null;
        var ajaxurl = "/Ajax/AjaxHandle.ashx?CommandName=";

        var onAjaxFailure = function () {
            ZYCLib.UI.MessageBox.Alert("执行过程中遇到了错误");

        };

        var errorCodeHandler = {
            Error5: function (json) {
                ZYCLib.UI.MessageBox.Alert(unescape(json.ErrorMessage), null,
                    function () {
                        location.href = ZYCLib.LoginUrl();
                    }, "身份认证失败");
            }
        };

        //自动处理返回结果
        var postData = function (actName, data, onSuccess, onComplete, onErrorCodeHandler, isPrivate) {

            var url = ajaxurl + actName;
            if (isPrivate) url += "&isPrivate=1";
            $.post(url, { Data: JSON.stringify(data) }, function (jsonResult) {

                if (jsonResult.ErrorCode > 0) {

                    if (typeof (top._isShowError) != undefined && top._isShowError && jsonResult.ErrorCode > 0) {
                        alert(jsonResult.ErrorMessage);
                        return;
                    }


                    //onErrorCodeHandler = onErrorCodeHandler || errorCodeHandler;
                    var tempHandler = $.extend({}, onErrorCodeHandler, errorCodeHandler); //合并两个对象
                    onErrorCodeHandler = tempHandler;
                    var handler = onErrorCodeHandler["Error" + jsonResult.ErrorCode];
                    console.log(actName);
                    if (!handler) handler = onErrorCodeHandler["Error"];

                    if (handler) handler(jsonResult);
                    else {
                        if (handler == undefined)
                            ZYCLib.UI.MessageBox.Alert(unescape(jsonResult.ErrorMessage));
                    }

                } else {
                    ZYCLib.CallBack(onSuccess, jsonResult.Data);
                    //ZYCLib.CallBack(onSuccess, jsonResult);
                }
            }, "json")
                .error(function (XMLHttpRequest) {
                    //状态码 
                    //0 － （未初始化）还没有调用send()方法 
                    //1 － （载入）已调用send()方法，正在发送请求 
                    //2 － （载入完成）send()方法执行完成，已经接收到全部响应内容 
                    //3 － （交互）正在解析响应内容 
                    //4 － （完成）响应内容解析完成，可以在客户端调用了
                    if (XMLHttpRequest.readyState != 0 && XMLHttpRequest.readyState != 0) {
                        onAjaxFailure();
                    }
                })
                .complete(function () {
                    ZYCLib.CallBack(onComplete);
                    //if (onComplete) onComplete();
                });
        };

        //手动处理返回结果
        var nPostData = function (actName, data, onSuccess, onComplete, onErrorCodeHandler, isPrivate) {
            var url = ajaxurl + actName;
            if (isPrivate) url += "&isPrivate=1";
            $.post(url, { Data: JSON.stringify(data) },
                function (jsonResult) {
                    ZYCLib.CallBack(onSuccess, jsonResult);
                }, "json")
                .error(function (XMLHttpRequest) {
                    //状态码 
                    //0 － （未初始化）还没有调用send()方法 
                    //1 － （载入）已调用send()方法，正在发送请求 
                    //2 － （载入完成）send()方法执行完成，已经接收到全部响应内容 
                    //3 － （交互）正在解析响应内容 
                    //4 － （完成）响应内容解析完成，可以在客户端调用了
                    if (XMLHttpRequest.readyState != 0 && XMLHttpRequest.readyState != 0) {
                        onAjaxFailure();
                    }
                })
                .complete(function () {
                    ZYCLib.CallBack(onComplete);
                });
        }


        var mvcRequest = function (url, sendData, sendType, isAsync, isShowLoad, callback, isJsonp, newHost) {

            try {

                if (isShowLoad) {
                    ShowLoading();
                }

                var ajaxObj = {};

                var defaultHost = "";

                if (isJsonp == false || isJsonp == undefined || isJsonp == null || isJsonp == "") {
                    isJsonp = false;
                } else {
                    isJsonp = true;
                    defaultHost = _PublicServerUrl;
                }

                if (newHost == undefined || newHost == null || newHost == "") {

                } else {

                    defaultHost = newHost;
                }


                url = defaultHost + url;
                ajaxObj.url = url;
                //sendData.MyToken = top._myToken;
                ajaxObj.data = sendData;
                ajaxObj.type = sendType;
                ajaxObj.async = isAsync;

                if (isJsonp) {
                    ajaxObj.dataType = "jsonp";
                    ajaxObj.jsonp = "jsoncallback";
                }

                ajaxObj.success = function (ret) {

                    if (isShowLoad) {
                        HideLoading();
                    }

                    if (typeof (top._isShowError) != undefined && top._isShowError && ret.ErrorCode > 0) {
                        alert(ret.ErrorMessage);
                        return;
                    }

                    if (typeof (callback) === "function") {
                        callback(ret.Data, ret);
                    }

                };

                ajaxObj.error = function (ret) {

                    if (isShowLoad) {
                        HideLoading();
                    }

                };

                $.ajax(ajaxObj);

            } catch (e) {

                if (isShowLoad) {
                    HideLoading();
                }



            }

        }

        var ShowLoading = function () {
            _winDefaultLoad = layer.load(0, 2);
        }

        var HideLoading = function (loadObj) {
            if (_winDefaultLoad != null) {
                layer.close(_winDefaultLoad);
            }
        }

        return {
            PostData: postData,
            NPostData: nPostData,
            MvcRequest: mvcRequest,
        };

    })();
    ZYCLib.RegNameSpace(namespace).Request = function () {
        var data, index;
        (function init() {
            data = [];
            index = {};
            var u = window.location.search.substr(1);
            if (u != "") {
                var parms = u.split("&");
                for (var i = 0, len = parms.length; i < len; i++) {
                    if (parms[i] != "") {
                        var p = parms[i].split("=");
                        if (p.length == 1 || (p.length == 2 && p[1] == "")) {
                            data.push("");
                            index[p[0]] = data.length - 1;
                        } else if (typeof (p[0]) == "undefined" || p[0] == "") {
                            data[0] = p[1];
                        } else if (typeof (index[p[0]]) == "undefined") {
                            //data.push(decodeURIComponent(decodeURIComponent(p[1])));
                            try {
                                data.push(decodeURIComponent(decodeURIComponent(p[1])));
                            } catch (ex) {
                                try {
                                    data.push(unescape(p[1]));
                                } catch (ex) {
                                    data.push(p[1]);
                                }

                            }
                            index[p[0]] = data.length - 1;
                        } else { // c=aaa&c=bbb  

                        }
                    }
                }
            }
        })();
        return {
            QueryParameter: function (o) {
                /// <summary>获得参数</summary>
                /// <param name="o">参数名或者参数次序</param>
                try {
                    return (typeof (o) == "number" ? data[o] : data[index[o]]);
                } catch (e) {
                    return "";
                }
            },
            QueryString: function (o) {
                /// <summary>获得参数值</summary>
                /// <param name="o">参数名或者参数次序</param>
                try {
                    var result = (typeof (o) == "number" ? data[o] : data[index[o]]);
                    return result != undefined ? result : "";
                } catch (e) {
                    return "";
                }
            },
            HasParameter: function (parmName) {
                /// <summary>是否包含某个参数</summary>

                if (!parmName) return window.location.search !== "";

                return typeof (parmName) == "string" ? typeof (index[parmName]) != "undefined" : false;
            },
            ToJSON: function () {
                var map = {};
                try {
                    for (var p in index) {
                        map[p] = data[index[p]];
                    }
                } catch (e) {
                }
                return map;
            }
        };
    }();
    ZYCLib.RegNameSpace(namespace).URL = function () {
        function _ConverJSON2URL(json, url) {

            //url = url || location.origin + location.pathname + "?";
            url = url || location.pathname;
            if (url.indexOf("?") === -1) url = url + "?";
            else {
                if (url.indexOf("&") !== -1) url = url + "&";
            }
            var urlParam = new ZYCLib.Text.StringBuilder(url);

            for (var p in json) {
                if (json[p] !== "") urlParam.Append(p).Append("=").Append(json[p]).Append("&");
            }
            urlParam.RemoveTail();
            var result = urlParam.ToString();
            return result;
        };

        function _AddParms(jsondata, url) {
            url = url || location.pathname;
            if (url.indexOf("?") == -1) url = url + "?";
            var json = ZYCLib.Web.Request.ToJSON();
            for (var p in jsondata) {
                json[p] = jsondata[p];
            }
            return _ConverJSON2URL(json, url);
        };

        function _GetURLQueryString(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return null;
        };

        return {
            GetURLQueryString: _GetURLQueryString,
            AddParm: _AddParms,
            AddParmsAndGoTo: function (json, url) {
                location.href = _AddParms(json, url);
            },
            ConverJSON2URL: _ConverJSON2URL,
            GoToPage: function (totalpages, domPageNum, pageUrlFormat) {
                var reg = /^\d+$/;
                if (totalpages < 1) totalpages = 1;
                var pagenum = $("#" + domPageNum).val();
                var curControlID = domPageNum.replace("txtPage", "");
                var tip = document.getElementById("ShowTip" + curControlID);
                console.log(tip);
                if (!reg.test(pagenum)) {
                    tip.innerHTML = "请输入数字!";
                    $("#" + domPageNum).focus(); return;
                }
                var pagenumValue = parseInt(pagenum);
                if (pagenumValue === 0) {
                    tip.innerHTML = "输入页数不能为0!";
                    $("#" + domPageNum).focus(); return;
                }
                if (pagenumValue > totalpages) {
                    tip.innerHTML = "输入页数不能超过最大页数:" + totalpages + "!";
                    $("#" + domPageNum).focus(); return;
                }
                location.href = pageUrlFormat.replace("{0}", pagenumValue);
            }
        };
    }();
})("Web");

(function (ns, $) {
    ZYCLib.RegNameSpace(ns).SingleSignOn = (function () {
        var domain = window.location.hostname.toLowerCase();
        var domExt = domain.substring(domain.lastIndexOf('.'));

        var item;
        var activePlatforms = [];
        var cacheName = "activePlatforms";
        var splitChar = ',';

        var getActivePlatforms = function () {
            if (activePlatforms.length > 0) return activePlatforms;

            var ps = ZYCLib.Utils.LocalStorage.GetCookie(cacheName);
            if (ps != "" && ps !== null && typeof ps !== "undefined") {
                activePlatforms = ps.split(splitChar);
            }

            return activePlatforms;
        };

        var setActivePlatforms = function (val) {
            activePlatforms = [];
            for (var i = 0, j = val.length; i < j; i++) {
                activePlatforms.push(val[i].SecureHref);
            }
            ZYCLib.Utils.LocalStorage.SetCookie(cacheName, activePlatforms.join(splitChar));
        };

        var jsonpAjax = function (url, cmd, data, onComplete) {
            var postdata = { CommandName: "UserSignService/" + cmd };
            if (data) postdata.Data = JSON.stringify(data);

            $.ajax({
                async: false,
                url: url,
                type: "GET",
                dataType: 'jsonp',
                jsonp: 'jsoncallback',
                data: postdata,
                timeout: 5000,
                complete: function () {
                    if (onComplete) onComplete();
                }
            });
        };

        var login = function (arrData, onLoginFinish) {
            //记录平台号到本地以便心跳河退出时调用
            setActivePlatforms(arrData);
            var j = arrData.length;
            if (arrData.length == 0) {
                if (onLoginFinish) onLoginFinish();
                return;
            }
            var i = j;
            for (var k = 0; k < j; k++) {
                var _tmpData = $.extend({}, arrData[k], { CrossSecureHref: ["https://secure", ZYCLib.Domain, "/Ajax/AjaxHandle.ashx"].join(""), CrossHref: ZYCLib.Domain });
                jsonpAjax(arrData[k].SecureHref, "CrossPlatformSignIn", _tmpData, function () {
                    i--;
                    if (i == 0)
                        if (onLoginFinish) onLoginFinish();
                });
            }
        };

        return {
            LoginSso: login,
            SignOut: function (onSignOutFinish) {
                var ps = getActivePlatforms();

                var c = ps.length;

                if (c === 0) {
                    if (onSignOutFinish) onSignOutFinish();
                    return;
                }


                for (var i = 0, j = ps.length; i < j; i++) {
                    jsonpAjax(ps[i], "SignOut", null, function () {
                        c--;
                        if (c <= 0)
                            if (onSignOutFinish) onSignOutFinish();
                    });
                }
            },
            HeartBeat: function () {
                var ps = getActivePlatforms();
                for (var i = 0, j = ps.length; i < j; i++) {
                    jsonpAjax(ps[i], "HeartBeat", { Title: document.title, Href: document.location.href });
                }
            }
        };

    })();
})("CrossDomain", jQuery);